const cloud = require('wx-server-sdk')

cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})

exports.main = async (event, context) => {
  const {detail} = event
  const {_id, archived, desc, nowPrice, oldPrice, picUrl, title} = detail
  let _detail = null
  // id存在视为更新
  if (_id) {
    _detail = await cloud.database().collection('goods')
    .where({_id})
    .update({
      data: {
        archived,
        desc,
        nowPrice,
        oldPrice,
        picUrl,
        title,
        updateTime: new Date()
      }
    })
  }else {
    _detail = await cloud.database().collection('goods')
    .add({
      data: {
        archived,
        desc,
        nowPrice,
        oldPrice,
        picUrl,
        title,
        creationTime: new Date(),
        number: 0,
        sales: 0,
        updateTime: new Date()
      }
    })
  }
  return _detail
}
